#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 64

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("param num is invalid.\n");
        exit(-1);
    }

    const char *srcFile = argv[1];
    const char *dstFile = argv[2];

    /* 判断源文件是否存在 */
    int ret = access(srcFile, F_OK);
    if (ret == -1)
    {
        printf("src file not exist.\n");
        exit(-1);
    }

    /* 判断源文件权限 */
    int dstMode = 0;
    ret = access(srcFile, R_OK);
    if (ret == 0)
    {
        printf("srcFile read permission.\n");
        dstMode |= S_IRUSR;
    }

    ret = access(srcFile, W_OK);
    if (ret == 0)
    {
        printf("srcFile write permission.\n");
        dstMode |= S_IWUSR;
    }

    ret = access(srcFile, X_OK);
    if (ret == 0)
    {
        printf("srcFile execute permission.\n");
        dstMode |= S_IXUSR;
    }

    /* 打开源文件 */
    int srcFd = open(srcFile, O_RDONLY);
    if (srcFd == -1)
    {
        printf("src file open error.\n");
        exit(-1);
    }

    /* 打开目标文件 */
    int dstFd = open(dstFile, O_WRONLY | O_CREAT | O_TRUNC, dstMode);
    if (dstFd == -1)
    {
        printf("dst file open error.\n");
        close(srcFd); // 确保源文件关闭
        exit(-1);
    }

    char buffer[BUFFER_SIZE];
    int readBytes = 0;
    while ((readBytes = read(srcFd, buffer, sizeof(buffer))) > 0)
    {
        write(dstFd, buffer, readBytes);
    }

    if (readBytes == -1)
    {
        printf("Error reading source file.\n");
    }

    /* 关闭文件 */
    close(srcFd);
    close(dstFd);

    return 0;
}
